import {Injectable} from '@angular/core';
import {HttpEvent, HttpResponse, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

import {tap} from 'rxjs/operators';

@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req);
  }
}

@Injectable()
export class HttpResponseInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req).pipe(
      tap((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          if (event.status >= 200 && event.status < 300) {
            console.log('%c请求成功', 'color: green;');
          } else if (event.status >= 300 && event.status < 400) {
            console.log('%c请求成功 使用缓存', 'color: green;');
          } else if (event.status >= 400 && event.status < 500) {
            console.log('%c请求出现错误', 'color: red;');
          } else if (event.status >= 500) {
            console.log('%c服务端错误', 'color: red;');
          }
        }
      })
    );
  }
}

